import time
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator, DateFormatter
from bqtool.test.tvcfile_to_mongodb import MongoBase
from bqtool.utils.tools import to_pdtime_ms

mongo = MongoBase('test',db='ai')
# mongo = MongoBase('test')


def find(startstr, endstr):
    startTime = pd.to_datetime(startstr)
    endTime = pd.to_datetime(endstr)
    start = int(startTime.tz_localize('Asia/Shanghai').value / 10 ** 6)
    end = int(endTime.tz_localize('Asia/Shanghai').value / 10 ** 6)
    data = mongo.collection.find({"gcsj": {"$gte": start, "$lt": end}})
    # data = mongo.collection.find({'TGSID' : tgsid})
    data = pd.DataFrame(list(data))
    if len(data) > 0:
        del data['_id']
        data['gcsj'] = to_pdtime_ms(data['gcsj'])
    # draw(data)
    print(len(data))


def draw(data):
    # data = get('1003_06_01')
    # .plot(kind='scatter', x='PASSTIME', y='DRIVEDIR')
    t = data[['PASSTIME', 'DRIVEDIR', 'DRIVEWAY']]
    t['DRIVEDIR'] = t['DRIVEDIR'].astype(str)
    t['DRIVEWAY'] = t['DRIVEWAY'].astype(str)
    # t['dir'] = t['DRIVEDIR'] + t['DRIVEWAY']
    # t['PASSTIME'] = t['PASSTIME'].dt.strftime('%Y-%m-%d %H:%M:%S')
    # s = t.groupby(['sec','dir']).size()
    t = t[t['DRIVEDIR'] != '99']
    t = t.set_index('PASSTIME')

    plt.scatter(t.index, t.DRIVEDIR, marker='.')
    ax = plt.gca()
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d %H:%M'))
    plt.xticks(rotation=60, ha='center')
    label = ['speedpoint']
    plt.legend(label, loc='upper right')
    plt.grid()

    plt.show()
    print(len(data))


def create_index(col):
    mongo.collection.create_index(col)
    print('create_index ok')


if __name__ == '__main__':
    start = time.clock()

    # create_index('TGSID')
    find('2018-05-11 11:00:00','2018-05-11 11:12:00')
    end = time.clock()
    print('Running time: %s Seconds' % (end - start))
